package com.example.myapplication2.dataBase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import com.example.myapplication2.DataBaseCRUDActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBHelper extends SQLiteOpenHelper {

    private static final String DB_NAME="user.db";
    private static final String TABLE_NAME="user_info";
    private static DBHelper dbHelper=null;
    private static final int DB_VER=3;
    private SQLiteDatabase sqLiteDatabaseRead=null;
    private SQLiteDatabase sqLiteDatabaseWrite=null;
    private DBHelper(Context context){
        super(context,DB_NAME,null,DB_VER);
    }
    //利用单例模式获取数据库帮助器的唯一实例
    public static DBHelper getInstance(Context context){
        if (dbHelper==null){
            dbHelper=new DBHelper(context);
        }
        return dbHelper;
    }
    //打开数据库读连接
    public SQLiteDatabase openReadLink(){
        if (sqLiteDatabaseRead==null||!sqLiteDatabaseRead.isOpen()){
            sqLiteDatabaseRead=dbHelper.getReadableDatabase();
        }
        return sqLiteDatabaseRead;
    }
    //打开数据库写连接
    public SQLiteDatabase openWriteLink(){
        if (sqLiteDatabaseWrite==null||!sqLiteDatabaseWrite.isOpen()){
            sqLiteDatabaseWrite=dbHelper.getWritableDatabase();
        }
        //获取版本
        int version = sqLiteDatabaseWrite.getVersion();
        System.out.println("版本:");
        System.out.println(version);
        return sqLiteDatabaseWrite;
    }
    //关闭连接
    public void closeLink(){
        if (sqLiteDatabaseWrite!=null||sqLiteDatabaseWrite.isOpen()){
            //关闭然后置空节约内存
            sqLiteDatabaseWrite.close();
            sqLiteDatabaseWrite=null;
        }
        if (sqLiteDatabaseRead!=null||sqLiteDatabaseRead.isOpen()){
            //关闭然后置空节约内存
            sqLiteDatabaseRead.close();
            sqLiteDatabaseRead=null;
        }
    }
    //创建
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        String sql="CREATE TABLE IF NOT EXISTS "+TABLE_NAME+" (" +
                " _id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
                "name VARCHAR NOT NULL," +
                "age INTEGER NOT NULL,height FLOAT NOT NULL," +
                "checkBox INTEGER NOT NULL);";
        sqLiteDatabase.execSQL(sql);
    }

    //更新数据表结构,仅仅是版本不一致的时候,Version must be >= 1, was 0
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        System.out.println("............");
        System.out.println(oldVersion);
        System.out.println(newVersion);
        System.out.println("............");
        System.out.println("被执行了");
        String sql="ALTER TABLE "+TABLE_NAME+" ADD COLUMN verK VARCHAR";
        sqLiteDatabase.execSQL(sql);
    }
    //新增
    public long insert(Map<String,Object> map){
        ContentValues values=new ContentValues();
        values.put("name", (String) map.get("name"));
        values.put("age", Integer.valueOf(map.get("age").toString()) );
        values.put("checkBox", (Boolean) map.get("checkBox"));
        values.put("height", Float.parseFloat((String) map.get("height")));
        long insert = -1;
        try{
            //开始事务
            sqLiteDatabaseWrite.beginTransaction();
            //第一个参数是表的名称
            //第二个参数为空值字段，就是如果第三个参数为空（null)的时候就会用到第二个参数的值。用第二个参数代替第三个参数组拼成SQL语句
            //比如：insert into person(name) values(null)   这里的person字段使用了第二个参数的name
            //第三个参数不为空就不会用到第二个参数
            insert = sqLiteDatabaseWrite.insert(TABLE_NAME, null, values);
            //设置操作成功
            sqLiteDatabaseWrite.setTransactionSuccessful();
        }catch (Exception e){

        }finally {
            //结束事务
            sqLiteDatabaseWrite.endTransaction();
        }
        return insert;
    }
    //修改
    public long update(Map<String,Object> map){

        ContentValues values=new ContentValues();
        values.put("name", (String) map.get("name"));
        values.put("age", Integer.valueOf(map.get("age").toString()) );
        values.put("checkBox", (Boolean) map.get("checkBox"));
        values.put("height", Float.parseFloat((String) map.get("height")));

        int id = sqLiteDatabaseWrite.update(TABLE_NAME, values, "_id=?", new String[]{(String) map.get("id")});
        return id;
    }
    //删除
    public int delete(Long id){
        //条件删除使用
        // int delete = sqLiteDatabaseWrite.delete(TABLE_NAME, "_id=? and age=?", new String[]{id.toString(),age});
        int delete = sqLiteDatabaseWrite.delete(TABLE_NAME, "_id=?", new String[]{id.toString()});
        return delete;
    }
    //根据ID查询
    public Map find(Long id){
        Map<String,Object> map=new HashMap();
        Cursor query = sqLiteDatabaseRead.query(TABLE_NAME, null, "_id=?", new String[]{id+""}, null, null, null);
        //判定查询为空否
        if (query.getCount()>0){
            //移动游标到第一条
            query.moveToFirst();
            map.put("id",query.getLong(0));
            map.put("name",query.getString(1));
            map.put("age",query.getInt(2));
            map.put("height",query.getFloat(3));
            int checkBoxInt = query.getInt(4);
            if (checkBoxInt==0){
                map.put("checkBox",false);
            }else if (checkBoxInt==1){
                map.put("checkBox",true);
            }
        }

        return map;
    }
    //查询所有
    public List<Map<String,Object>> findAll(){

        List<Map<String, Object>> list=new ArrayList<>();
        Cursor query = sqLiteDatabaseRead.query(TABLE_NAME, null, null, null, null, null, null);
        while (query.moveToNext()) {
            Map<String,Object> map=new HashMap<>();
            map.put("id",query.getLong(0));
            map.put("name",query.getString(1));
            map.put("age",query.getInt(2));
            map.put("height",query.getFloat(3));
            int checkBoxInt = query.getInt(4);
            if (checkBoxInt==0){
                map.put("checkBox",false);
            }else if (checkBoxInt==1){
                map.put("checkBox",true);
            }
            list.add(map);
        }

        return list;
    }
}
